<?php
/**
 * Created by PhpStorm.
 * User: tsang
 * Date: 2018/3/15
 * Time: 10:27
 */

namespace app\api\logic;
use think\Cache;
use think\Request;
use app\api\validate\Personal as PersonalValidate;

class Personal extends \app\api\BaseModel
{

    /*
    我的
     */
    public function personal_center(){
        $data = array();

        //获取赞数
        $where['fc.user_id']=$this->user['userId'];
        $where['fcp.type']=0;
        $result = db('foods_circle_praise')->alias('fcp')
            ->join("foods_circle fc","fc.id = fcp.circle_id")
            ->where($where)
            ->count("fcp.id");

        $data['praise_count'] = $result;

        //获取关注数
        $attention_count = $this->attention_count();

        $data['attention_count'] = $attention_count;

        //粉丝数
        $fans_count = $this->fans_count();

        $data['fans_count'] = $fans_count;

        //查询用户详情
        $member_result = db('member')->where(array('id'=>$this->user['userId']))->field('background,nickname,headimage,spend_calories')->find();

        $data['nickname'] = $member_result['nickname'];
        $data['headimage'] = get_headimage($member_result['headimage'],$this->user['userId']);
        $data['spend_calories'] = $member_result['spend_calories'];

        //客服电话
        $about = db('about')->where(array('id'=>1))->field('tel')->find();

        //是否有新的系统消息
        $system_read = db('system_read')->where(array('user_id'=>$this->user['userId']))->count();
        $system_count = db('system_letter')->count();

        if($system_read != $system_count){
            $data['is_system_read'] = 1;
        }else{
            $data['is_system_read'] = 0;
        }

        if(isset($this->user['background'])){
            $data['background'] = IMG_PATH.str_replace('\\',"/",$this->user['background']);
        }else{
            $data['background'] = '';
        }

        $data['tel'] = $about['tel'];

        return $data;
    }




    /*
    我的优惠卷
     */
    public function coupon_list()
    {
        if (!isset($this->requestData['page'])) {
            $page = 1;
        } else {
            $page = $this->requestData['page'];
        }

        if (!isset($this->requestData['limit'])) {
            $limit = 10;
        } else {
            $limit = $this->requestData['limit'];
        }


        $page_start = ($page-1)*$limit;

        $where['user_id'] = $this->user['userId'];

        if(array_key_exists('type',$this->requestData)){
            switch (intval($this->requestData['type'])){
                case 1://未使用
                    $where['status'] = 0;
                    break;
                case 2://过期/已使用
                    $where['status'] = array('in',[-1,1]);
                    break;
            }
        }

        //查询全部
        $model = db('myvoucher');
        $total = $model->where($where)->count();

        //总页码
        $total_page = ceil($total/$limit);

        $result = $model->where($where)->limit($page_start,$limit)->field('id, name, money, fullmoney, start_time, end_time, status')->order("id desc")->select();

        foreach($result as $key=>$value){
            $result[$key]['start_time'] = date('Y.m.d',$value['start_time']);
            $result[$key]['end_time'] = date('Y.m.d',$value['end_time']);

            if(time()>$value['end_time'] && $value['status']=='0'){
                //如果该优惠卷已过期则做过期处理又没使用则过期
                $model->where(array('id'=>$value['id']))->update(array('status'=>'-1'));
                $result[$key]['status'] = '-1';
            }
        }

        $data['list'] = $result;
        $data['total_page'] = $total_page;
        $data['page'] = $page;
        $data['limit'] = $limit;

        return $data;
    }

    /*
    系统生成的优惠卷
     */
    public function system_coupon()
    {
        if(!isset($this->requestData['page'])){
            $page=1;
        }else{
            $page=$this->requestData['page'];
        }

        $limit = 10;

        $page_start = ($page-1)*$limit;

        $where['status'] = 1;
        $where['delete'] = 0;
        $where['count'] = array('>','0');

        //搜索已领取
        $voucher_ids = db('myvoucher')->where(array('user_id'=>$this->user['userId']))->field('voucher_id')->select();
        $voucher_ids = array_column($voucher_ids, 'voucher_id');
        $where['id'] = array('not in',$voucher_ids);

        $total = db('voucher')->where($where)->count();

        $total_page = ceil($total/$limit);

        $result = db('voucher')->where($where)->limit($page_start,$limit)->field('id,name,deduction,count,useful_day,fullmoney')->order('create_time desc')->select();

        $data['list'] = $result;
        $data['total_page'] = $total_page;
        $data['page'] = $page;


        return $data;
    }

    /*
    领取优惠卷
     */
    public function get_coupon()
    {
        (new PersonalValidate())->checkGetCouponParam();

        $vid=$this->requestData['vid'];

        $result = db('voucher')->where(array('id'=>$vid))->field('name,useful_day,delete,status,count,deduction,fullmoney')->find();

        if($result['delete'] == 1)return array('message'=>'该优惠卷已删除，不能领取!');
        if($result['status'] == 0)return array('message'=>'该优惠卷已停用，不能领取!');
        if($result['count'] <= 0)return array('message'=>'该优惠卷已领完了!');

        if(empty($result))return array('message'=>'该优惠卷已删除,不能领取');

        $myvoucher_result = db('myvoucher')->where(array('voucher_id'=>$vid,'user_id'=>$this->user['userId']))->find();

        if(!empty($myvoucher_result))return array('message'=>'该优惠卷你已领取过了!');

        $data['voucher_id'] = $vid;
        $data['name'] = $result['name'];
        $data['fullmoney'] = $result['fullmoney'];
        $data['user_id'] = $this->user['userId'];
        $data['money'] = $result['deduction'];
        $data['start_time'] = time();
        //有效天数
        $useful_day = $result['useful_day'];
        $data['end_time'] = time()+(86400*$useful_day);
        $data['status'] = 0;

        $res = db('myvoucher')->insert($data);

        if($res){
            //领取以后优惠卷减一
            db('voucher')->where(array('id'=>$vid))->setDec('count');
        }

        if(!$res)return array('message'=>'领取优惠卷失败');
    }



    /*
    修改资料
     */
    public function changeInformation()
    {
        if(!isset($this->requestData['param']))return array('message'=>'缺少param参数');

        $param = $this->requestData['param'];

        $param_bool = array('change_sex','change_nickname','change_headimage','change_age','change_height','change_weight','change_physical_activity','change_like_dish','change_dish_type','change_figure','change_background','change_taste');

        //检测是否修改身高，体重，年龄，性别 修改了需要重新计算
        $param_brm = array('change_age','change_height','change_weight','change_sex','change_physical_activity');

        if(in_array($param,$param_bool)){

            $where['id'] = $this->user['userId'];
            $data = array();

            //查询账号
            $chat_result = db('chat')->where(array('typeid'=>$this->user['userId']))->field('userid')->find();

            switch ($param) {
                case 'change_headimage':
                    //换头像
                    $file=Request::instance()->file('headimage');

                    if($file){
                        $info = $file->move(ROOT_PATH . 'public/static/uploads');

                        if($info){
                            $data['headimage']= request()->domain().'/static/uploads/'.str_replace('\\',"/",$info->getSaveName());
                        }
                    }else{
                        return array('message'=>'修改失败');
                    }
                    break;
                case 'change_nickname':
                    //换昵称
                    if(!isset($this->requestData['change_nickname']))return array('message'=>'缺少change_nickname');
                    $change_nickname = $this->requestData['change_nickname'];
                    if(mb_strlen($change_nickname,'utf-8')>10){
                        return array('message'=>'昵称不能超过10个字');
                    }
                    $root = db('member')->where(array('nickname'=>$change_nickname))->find();
                    if(!empty($root))return array('message'=>'该昵称已被使用!');

                    $data['nickname'] = $change_nickname;
                    break;
                case 'change_age':
                    //换岁数
                    if(!isset($this->requestData['age']))return array('message'=>'缺少age');
                    $age = $this->requestData['age'];
                    $data['age'] = $age;
                    break;
                case 'change_height':
                    //修改身高
                    if(!isset($this->requestData['height']))return array('message'=>'缺少height');
                    $height = $this->requestData['height'];
                    $data['height'] = $height;
                    break;
                case 'change_weight':
                    //修改体重
                    if(!isset($this->requestData['weight']))return array('message'=>'缺少weight');
                    $weight = $this->requestData['weight'];
                    $data['weight'] = $weight;
                    break;
                case 'change_physical_activity':
                    //修改运动方式
                    if(!isset($this->requestData['physical_activity']))return array('message'=>'缺少physical_activity');
                    $physical_activity = $this->requestData['physical_activity'];
                    $data['physical_activity'] = $physical_activity;
                    break;
                case 'change_like_dish':
                    //修改自己喜欢的菜
                    if(!isset($this->requestData['like_dish']))return array('message'=>'缺少like_dish');
                    $like_dish = $this->requestData['like_dish'];
                    $data['like_dish'] = $like_dish;
                    break;
                case 'change_dish_type':
                    //修改菜类型
                    if(!isset($this->requestData['dish_type']))return array('message'=>'缺少dish_type');
                    $dish_type = $this->requestData['dish_type'];
                    $data['dish_type'] = $dish_type;
                    break;
                case 'change_figure':
                    //身材追求
                    if(!isset($this->requestData['figure']))return array('message'=>'缺少figure');
                    $figure = $this->requestData['figure'];
                    $data['figure'] = $figure;
                    break;
                case 'change_taste':
                    //口味
                    if(!isset($this->requestData['taste']))return array('message'=>'缺少taste');
                    $taste = $this->requestData['taste'];
                    $data['taste'] = $taste;
                    break;
                case 'change_sex':
                    //修改性别
                    if(!isset($this->requestData['sex']))return array('message'=>'缺少sex');
                    $sex = $this->requestData['sex'];
                    $data['sex'] = $sex;
                    break;
                case 'change_background':
                    $file=Request::instance()->file('change_background');

                    if($file){
                        $info = $file->move(ROOT_PATH . 'public/static/uploads');

                        if($info){
                            $data['background']= "/".str_replace('\\',"/",$info->getSaveName());
                        }
                    }else{
                        return array('message'=>'修改失败');
                    }
                    break;
                default:
                    # code...
                    break;
            }

            //假如修改了相关身体数据则修改卡路里数据
            if(in_array($param, $param_brm)){
                $member_result = db('member')->where(array('id'=>$this->user['userId']))->find();

                if(isset($data['physical_activity'])){
                    $member_result['physical_activity'] = $data['physical_activity'];
                }

                switch ($member_result['physical_activity']) {
                    case '1':
                        //几乎不动(每周运动0次)
                        $brm = 1.2;
                        break;
                    case '2':
                        $brm = 1.375;
                        break;
                    case '3':
                        $brm = 1.55;
                        break;
                    case '4':
                        $brm = 1.725;
                        break;
                    case '5':
                        $brm = 1.9;
                        break;
                    default:
                        $brm =1.2;
                        break;
                }


                //计算卡路里
                if($member_result['sex'] == '1'){
                    //男: BMR = 66 + ( 13.7 x 体重kg ) + ( 5 x 身高cm ) - ( 6.8 x 年龄years )
                    $data['spend_calories'] = 66 + (13.7 * $member_result['weight']) + (5 * $member_result['height']) - (6.8 * $member_result['age']);
                }else{
                    //女: BMR = 655 + ( 9.6 x 体重kg ) + ( 1.8 x 身高cm ) - ( 4.7 x 年龄years )
                    $data['spend_calories'] = 655 + (9.6 * $member_result['weight']) + (1.8 * $member_result['height']) - (4.7 * $member_result['age']);
                }

                $data['spend_calories'] = $data['spend_calories'] * $brm;
            }

            $bool = db('member')->where($where)->update($data);
            if(!$bool) return array('message'=>'修改失败');

            if($param == 'change_nickname'){
                //修改百川聊天
                $result = (new \app\api\logic\Chat())->set_user($data,$chat_result['userid']);

                if(array_key_exists('message',$result)){
                    return array('message'=>'修改失败');
                }

                if(isset($result['uid_fail'])){
                    return array('message'=>'修改失败');
                }
            }

            if($param == 'change_headimage'){
                //修改百川聊天
                $change_touxiang['headimage_url'] = $data['headimage'];

                $result = (new \app\api\logic\Chat())->set_user($data,$chat_result['userid']);

                if(array_key_exists('message',$result)){
                    return array('message'=>'修改失败');
                }

                if(isset($result['uid_fail'])){
                    return array('message'=>'修改失败');
                }
                return $change_touxiang;
            }

            if($param == 'change_background'){
                $change_background = array();
                $change_background['change_background'] = IMG_PATH.str_replace('\\',"/",$data['background']);
                return $change_background;
            }
        }else{

            return array('message'=>'param参数错误');
        }
    }

    /*
    *资料详情
    */
    public function userInfomation()
    {
        $where['id'] = $this->user['userId'];

        $result = db('member')->where($where)->field('headimage,nickname,sex,background,height,weight,physical_activity,age,like_dish,dish_type,figure,taste')->find();
        $result['headimage'] = get_headimage($result['headimage'],$this->user['userId']);
        if(isset($this->user['background'])){
            $result['background'] = IMG_PATH.str_replace('\\',"/",$this->user['background']);
        }else{
            $result['background'] = '';
        }

        //判断资料是否完善
        if(!empty($result['headimage']) && !empty($result['nickname']) && !empty($result['sex']) && !empty($result['age']) && !empty($result['height']) && !empty($result['weight']) && !empty($result['physical_activity'])){
            $result['is_perfect'] = 1;
        }else{
            $result['is_perfect'] = 0;
        }

        return $result;
    }

    /*
      *	第三方绑定
      */
    public function bind(){
        $type=$this->requestData['type'];
        if($type==0) {
            $where['wx_openid'] = $this->requestData['openid'];
        }
        if($type==1) {
            $where['qq_openid'] = $this->requestData['openid'];
        }
        if($type==2) {
            $where['wb_openid'] = $this->requestData['openid'];
        }
        $where['delete'] = 1;
        $where['id'] = array("neq",$this->user['uid']);
        $member = db('member')->where($where)->find();
        if($member) return array('message'=>'已绑定了其他账户');
        $insert = db('member')->where("id=".$this->user['uid'])->update($where);
        if($insert===false) return array('message'=>'绑定失败');
        return array();

    }

    /*
    系统消息详情
     */
    public function system_letter()
    {
        if(!isset($this->requestData['page'])){
            $page=1;
        }else{
            $page=$this->requestData['page'];
        }

        $limit = 10;

        $page_start = ($page-1)*$limit;

        //查询全部
        $total = db('system_letter')->count();

        //总页码
        $total_page = ceil($total/$limit);

        $result = db('system_letter')->limit($page_start, $limit)->order('creatime desc')->select();

        foreach ($result as $key => $value) {
            $system_read_result = db('system_read')->where(array('user_id'=>$this->user['userId'],'suggestion_id'=>$value['id']))->find();
            if(empty($system_read_result)){
                $result[$key]['is_read'] = '0';
            }else{
                $result[$key]['is_read'] = '1';
            }
            $result[$key]['creatime'] = date('Y年m月d日',$value['creatime']);
        }

        $data['list'] = $result;
        $data['total_page'] = $total_page;

        return $data;
    }

    /*
    系统详情
     */
    public function system_info()
    {

        $sid=$this->requestData['sid'];

        $result = db('system_letter')->where(array('id'=>$sid))->find();

        $is_read = db('system_read')->where(array('user_id'=>$this->user['userId'],'suggestion_id'=>$sid))->find();

        if(empty($is_read)){
            $data['user_id']=$this->user['userId'];
            $data['suggestion_id']=$sid;

            db('system_read')->insert($data);
        }

        $result['creatime'] = date('Y年m月d日',$result['creatime']);

        return $result;
    }
}